package com.cyt.sys.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.dao.BaseUserTokenDao;
import com.cyt.sys.model.po.SysUserToken;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.model.vo.SysUserTokenVo;
import com.cyt.sys.service.SysUserTokenService;
import com.cyt.sys.util.TokenGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 系统模块-用户TokenService层实现类
 *
 * @author congcong tao
 * @date 2019-4-24 9:38:22
 */
@Service("baseUserTokenService")
public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserToken> implements SysUserTokenService {

    @Resource
    private BaseUserTokenDao baseUserTokenDao;

    @Autowired
    public void setBaseDao(BaseUserTokenDao baseUserTokenDao) {
        this.baseDao = baseUserTokenDao;
    }

    /**
     * 12小时后过期
     */
    private final static int EXPIRE = 3600 * 12;

    /**
     * 查询对象集合
     *
     * @param sysUserTokenVo 对象
     * @return List 对象集合
     * @author congcong tao
     * @date 2019-4-24 9:38:22
     */
    @Override
    public List<SysUserToken> listExample(SysUserTokenVo sysUserTokenVo) {
        Example example = new Example(SysUserToken.class);
        example.setOrderByClause(" update_time desc");
        Example.Criteria criteria = example.createCriteria();
        return baseUserTokenDao.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param sysUserTokenVo 接受参数对象
     * @param pageNum         分页数
     * @param pageSize        每页显示条数
     * @return ReturnResult
     * @author congcong tao
     * @date 2019-4-24 9:38:22
     */
    @Override
    public ReturnResult page(SysUserTokenVo sysUserTokenVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" update_time desc");
        List<SysUserToken> list = listExample(sysUserTokenVo);
        PageInfo<SysUserToken> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param sysUserTokenVo 参数接受对象
     * @param currentUser     当前用户
     * @return ReturnResult
     * @author congcong tao
     * @date 2019-4-24 9:38:22
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(SysUserTokenVo sysUserTokenVo, SysUser currentUser) {
        if (StrUtil.isEmpty(sysUserTokenVo.getId())) {
            SysUserToken sysUserToken = new SysUserToken();
            sysUserToken.setToken(sysUserTokenVo.getToken());
            sysUserToken.setExpireTime(DateUtil.parseTime(sysUserTokenVo.getExpireTime()));
            int num = baseUserTokenDao.insert(sysUserToken);
            if (num > 0) {
                return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
            } else {
                return new ReturnResult(ErrorCode.CODE_1, BaseConstant.DATABASE_ERROR_INSERT);
            }
        } else {
            SysUserToken sysUserToken = baseUserTokenDao.selectByPrimaryKey(sysUserTokenVo.getId());
            sysUserToken.setToken(sysUserTokenVo.getToken());
            sysUserToken.setExpireTime(DateUtil.parseTime(sysUserTokenVo.getExpireTime()));
            sysUserToken.setUpdateTime(new Date());
            int num = baseUserTokenDao.updateByPrimaryKey(sysUserToken);
            if (num > 0) {
                return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
            } else {
                return new ReturnResult(ErrorCode.CODE_1, BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
    }

    /**
     * 根据主键id集合软删除
     *
     * @param ids         主键id集合，多个以‘，’隔开
     * @param currentUser 当前用户
     * @return ReturnResult
     * @author congcong tao
     * @date 2019-4-24 9:38:22
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult deleteByIds(String ids, SysUser currentUser) {
        String[] idList = ids.split(",");
        for (String id : idList) {
            int num = baseUserTokenDao.deleteByPrimaryKey(id);
            if (num <= 0) {
                return new ReturnResult(ErrorCode.CODE_1, BaseConstant.DATABASE_SUCCEED_DEL);
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_ERROR_DEL);
    }

    @Override
    public SysUserToken selectByToken(String token) {
        SysUserToken record = new SysUserToken();
        record.setToken(token);
        List<SysUserToken> sysUserTokenList = baseUserTokenDao.select(record);
        if (sysUserTokenList != null && sysUserTokenList.size() > 0) {
            return sysUserTokenList.get(0);
        }
        return null;
    }

    @Override
    public ReturnResult insertToken(String userId) {
        // 生成一个token
        String token = TokenGenerator.generateValue();
        // 当前时间
        Date now = new Date();
        // 过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        // 判断是否生成过token
        SysUserToken tokenEntity = baseUserTokenDao.selectByPrimaryKey(userId);
        if (tokenEntity == null) {
            tokenEntity = new SysUserToken();
            tokenEntity.setId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            // 保存token
            baseUserTokenDao.insert(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            // 更新token
            baseUserTokenDao.updateByPrimaryKeySelective(tokenEntity);
        }
        return new ReturnResult(token);
    }
}